import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { isTokenExpired } from '../utils/tokenUtils'

export const useUserStore = defineStore('user', () => {
  // 状态
  const currentUser = ref({
    id: null,
    username: '',
    nickname: '',
    email: '',
    phone: '',
    name: '',
    role: '',
    roles: [],
    avatar: ''
  })

  const isLoggedIn = ref(false)
  const isInitialized = ref(false)

  // 计算属性
  const isAdmin = computed(() => {
    return currentUser.value.roles?.includes('ADMIN') || currentUser.value.role === 'ADMIN'
  })

  const isUser = computed(() => {
    return currentUser.value.roles?.includes('USER') || currentUser.value.role === 'USER'
  })

  // 同步localStorage和Pinia状态的核心方法
  const syncFromStorage = () => {
    const token = localStorage.getItem('token')
    const userInfo = localStorage.getItem('userInfo')

    if (!token || !userInfo) {
      clearUserState()
      return false
    }

    try {
      // 同步检查token是否有效
      if (isTokenExpired(token)) {
        console.log('Token已过期，清除登录状态')
        clearUserState()
        return false
      }

      const parsedUserInfo = JSON.parse(userInfo)
      updateUserState(parsedUserInfo, true)
      console.log('从localStorage同步用户状态成功')
      return true
    } catch (error) {
      console.error('解析用户信息失败:', error)
      clearUserState()
      return false
    }
  }

  // 更新用户状态（同时更新Pinia和localStorage）
  const updateUserState = (userInfo, skipStorageUpdate = false) => {
    currentUser.value.id = userInfo.id
    currentUser.value.username = userInfo.username || userInfo.name
    currentUser.value.nickname = userInfo.nickname || ''
    currentUser.value.email = userInfo.email || ''
    currentUser.value.phone = userInfo.phone || ''
    currentUser.value.name = userInfo.name || userInfo.nickname
    currentUser.value.role = userInfo.role
    currentUser.value.roles = userInfo.roles || []
    currentUser.value.avatar = userInfo.avatar || ''
    isLoggedIn.value = true

    // 同步到localStorage（除非明确跳过）
    if (!skipStorageUpdate) {
      localStorage.setItem('userInfo', JSON.stringify(userInfo))
    }
  }

  // 清除用户状态（同时清除Pinia和localStorage）
  const clearUserState = () => {
    currentUser.value = {
      id: null,
      username: '',
      nickname: '',
      email: '',
      phone: '',
      name: '',
      role: '',
      roles: [],
      avatar: ''
    }
    isLoggedIn.value = false

    // 清除localStorage
    localStorage.removeItem('token')
    localStorage.removeItem('refreshToken')
    localStorage.removeItem('userInfo')
  }

  // 初始化用户状态（统一入口）
  const initializeAuth = () => {
    if (isInitialized.value) {
      return Promise.resolve()
    }

    return new Promise((resolve) => {
      const success = syncFromStorage()
      isInitialized.value = true
      resolve(success)
    })
  }

  // 登录方法（设置用户状态和token）
  const login = (userInfo, token, refreshToken) => {
    // 先设置token到localStorage
    localStorage.setItem('token', token)
    localStorage.setItem('refreshToken', refreshToken)

    // 更新用户状态
    updateUserState(userInfo)

    // 启动token自动刷新
    import('../utils/tokenUtils').then(({ startTokenRefresh }) => {
      startTokenRefresh()
    }).catch(error => {
      console.error('启动token自动刷新失败:', error)
    })

    // 启动WebSocket连接
    import('../utils/websocket').then(({ default: webSocketManager }) => {
      webSocketManager.connect(token).then(() => {
        console.log('WebSocket连接已建立')
      }).catch(error => {
        console.error('WebSocket连接失败:', error)
      })
    }).catch(error => {
      console.error('WebSocket模块导入失败:', error)
    })
  }

  // 登出方法
  const logout = () => {
    clearUserState()

    // 停止token自动刷新
    import('../utils/tokenUtils').then(({ stopTokenRefresh }) => {
      stopTokenRefresh()
    }).catch(() => {
      // 忽略导入错误
    })

    // 断开WebSocket连接
    import('../utils/websocket').then(({ default: webSocketManager }) => {
      webSocketManager.disconnect()
    }).catch(() => {
      // 忽略导入错误
    })

    // 清除权限状态
    import('./permission').then(({ clearPermissions }) => {
      clearPermissions()
    }).catch(() => {
      // 忽略导入错误
    })

    // 清除动态路由
    import('../router/index').then(({ clearDynamicRoutes }) => {
      clearDynamicRoutes()
    }).catch(() => {
      // 忽略导入错误
    })
  }

  // 更新token（用于token刷新时同步状态）
  const updateTokens = (token, refreshToken) => {
    localStorage.setItem('token', token)
    localStorage.setItem('refreshToken', refreshToken)
  }

  // 兼容性方法（保持向后兼容）
  const setCurrentUser = (userInfo) => {
    updateUserState(userInfo)
  }

  // 设置初始化状态
  const setInitialized = (value) => {
    isInitialized.value = value
  }

  return {
    // 状态
    currentUser,
    isLoggedIn,
    isInitialized,

    // 计算属性
    isAdmin,
    isUser,

    // 方法
    initializeAuth,
    login,
    logout,
    updateTokens,
    syncFromStorage,
    updateUserState,
    clearUserState,
    setInitialized,

    // 兼容性方法
    setCurrentUser
  }
})